<?php

/**
 *   OPENSHOP  呼叫中心管理员信息以及权限管理程序
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: cc_privilege.php,v 1.0 2009/08/25 15:35:58 modified $
 *   @author      Jiajun <jiajun@baison.com.cn>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/cc_init.php');

$username = isset($_GET['agentname']) ? $_GET['agentname'] : '';   //用户名
$password = isset($_GET['logoninfo']) ? $_GET['logoninfo'] : '';  //加密 后的密码
 
/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'signin';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

/*------------------------------------------------------ */
//-- 登陆界面
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'login')
{
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");

    if ((intval($_CFG['captcha']) & CAPTCHA_ADMIN) && gd_version() > 0)
    {
        $smarty->assign('gd_version', gd_version());
        $smarty->assign('random',     mt_rand());
    }
    $smarty->display('login.tpl');
}

/*------------------------------------------------------ */
//-- 验证登陆信息
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'signin')
{
    if (!empty($_SESSION['captcha_word']) && (intval($_CFG['captcha']) & CAPTCHA_ADMIN))
    {
        include_once(ROOT_PATH . 'includes/cls_captcha.php');

        /* 检查验证码是否正确 */
        $validator = new captcha();
        if (!empty($_POST['captcha']) && !$validator->check_word($_POST['captcha']))
        {
			$links[0]['text'] = '返回上一页';
		    $links[0]['href'] = 'javascript:history.go(-1)';
		    $links[0]['flag'] = 'login_failed';
		    sys_msg('您输入的验证码不正确。', 1, $links);
        }
    } 

    /* 检查密码是否正确 */
    $sql = "SELECT user_id, user_name, password, last_login, action_list, last_login".
            " FROM " . $os->table('admin_user') .
            " WHERE user_name = '" . $username. "' "; // AND password = '" .$password . "'

    $encode="LogonCorpNameUniquePaiAgentName" . $username ."Password";  
    
//    if(   $_GET['corpname']  != ""   )
//    {
//      $encode="LogonCorpName".$_GET("corpname")."AgentName" . $username ."Password";  	 die( $_GET['corpname']);
//    } 
    
    $row = $db->getRow($sql);
    //echo ($sql );
   // die(  $encode . strtoupper($row['password']) ." <br/>".strtoupper(  md5($encode . strtoupper($row['password']) ) )); 
    if ($row &&  strtoupper(  md5($encode . strtoupper($row['password'])) )== $password  )
    { 
    	if($row['action_list'] == 'all'){
			$action_list = $row['action_list'];
			$role_str = '超级管理员';
    	}else{
    		
		    $privilege_arr = $db->getAll("SELECT r_f.action_id FROM " . $os->table('acl_role_func') . " r_f LEFT JOIN" . $os->table('acl_role_user') . 
		                        " r_u ON r_u.role_id=r_f.role_id WHERE r_u.user_id=".intval($row['user_id']));		      
		    if($privilege_arr){
			    $act_list = array();
				while (list($key, $val) = each($privilege_arr)) {
				    array_push($act_list, $val['action_id']);
				}
		        $action_list = trim(((sizeof($act_list)>0)  ?  join(',', $act_list)  :  0), ',');
		    }else{
		    	$action_list = '0';
		    }	
		    
		    $arr_roles = $db->getAll("SELECT r.role_name FROM " . $os->table('acl_role_user') . " r_u LEFT JOIN" . $os->table('acl_role') . 
		                        " r ON r_u.role_id=r.role_id WHERE r_u.user_id=".intval($row['user_id']));	
		    if($arr_roles){
			    $roles_list = array();
				while (list($key, $val) = each($arr_roles)) {
				    array_push($roles_list, $val['role_name']);
				}
		        $role_str = trim(((sizeof($roles_list)>0)  ?  join(',', $roles_list)  :  '黑客'), ',');
		    }else{
		    	$role_str = '黑客';
		    }		    
    	}
    	
    	// 登录成功
        set_admin_session($row['user_id'], $row['user_name'], $action_list, $role_str, $row['last_login']);

        if($row['action_list'] == 'all' && empty($row['last_login']))
        {
            $_SESSION['shop_guide'] = true;
        }

        // 更新最后登录时间和IP
        $db->query("UPDATE " .$os->table('admin_user').
                 " SET last_login='" . gmtime() . "', last_ip='" . real_ip() . "'".
                 " WHERE user_id='$_SESSION[admin_id]'");

        if (isset($_POST['remember']))
        {
            $time = gmtime() + 3600 * 24 * 365;
            setcookie('OS_ADMIN[admin_id]',   $row['user_id'],                            $time);
            setcookie('OS_ADMIN[admin_pass]', md5($row['password'] . $_CFG['hash_code']), $time);
        }

        // 清除购物车中过期的数据
        clear_cart(); 
        os_header("Location: ./index.php\n");

        exit;
    }
    else
    {
    	$links[0]['text'] = '返回上一页';
        $links[0]['href'] = './index.php';
        $links[0]['flag'] = 'login_failed';
        /* 清除cookie */
    	setcookie('OS_ADMIN[admin_id]',   '', 1);
    	setcookie('OS_ADMIN[admin_pass]', '', 1);

        $sess->destroy_session();

        $_REQUEST['act'] = 'login';
                
        sys_msg('您输入的帐号信息不正确。', 1, $links);

    }
}

/* 获取管理员列表 */
function get_admin_userlist()
{
    $list = array();
    $sql  = 'SELECT user_id, user_name, email, add_time, last_login '.
            'FROM ' .$GLOBALS['os']->table('admin_user').' ORDER BY user_id DESC';
    $list = $GLOBALS['db']->getAll($sql);

    foreach ($list AS $key=>$val)
    {
        $list[$key]['add_time']     = local_date($GLOBALS['_CFG']['time_format'], $val['add_time']);
        $list[$key]['last_login']   = local_date($GLOBALS['_CFG']['time_format'], $val['last_login']);
    }

    return $list;
}

/* 清除购物车中过期的数据 */
function clear_cart()
{
    /* 取得有效的session */
    $sql = "SELECT DISTINCT session_id " .
            "FROM " . $GLOBALS['os']->table('cart') . " AS c, " .
                $GLOBALS['os']->table('sessions') . " AS s " .
            "WHERE c.session_id = s.sesskey ";
    $valid_sess = $GLOBALS['db']->getCol($sql);

    // 删除cart中无效的数据
    $sql = "DELETE FROM " . $GLOBALS['os']->table('cart') .
            " WHERE session_id NOT " . db_create_in($valid_sess);
    $GLOBALS['db']->query($sql);
}
?>
